﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using JibberJabber.PartDesigners;

namespace JibberJabber.LivePreviews
{
    internal abstract class PreviewTemplate
    {
        internal void RunPreview()
        {
            try
            {
                TempConversation t = beginPreviewCreate();
                configureTempConversation(t);
                endPreviewCreate(t);
            }
            catch (Exception exc)
            {
                MessageBox.Show("An Exception was thrown when trying to build a live preview.\n"
                    + "This could be construed as a bug. Please undo whatever you just did!\n\n"
                    + exc.ToString(),
                    "Live Preview Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Remember: configureTempConversation has Exceptions neatly handled,
        /// the constructor does not!
        /// </summary>
        /// <param name="tc"></param>
        protected abstract void configureTempConversation(TempConversation tc);

        protected void checkOk(PartDesigner pd)
        {
            if (pd.AssociatedNode == null)
                throw new Exception("Live previewing called for PartDesigner where "
                    + "AssociatedNode == null -- it's a temporary partdesigner, not"
                    + " a real one! You gots to check before you preview, soz. :(");
        }

        private TempConversation beginPreviewCreate()
        {
            // Order's important. clearfuckingeverything will kill any e.g.
            // created tempconversations before it! (or rather dispose their 
            // dialog sprites).
            Program.Preview.Pause();
            Program.Preview.ClearFuckingEverything();
            TempConversation tc = new TempConversation();
            return tc;
        }

        private void endPreviewCreate(TempConversation tc)
        {
            Program.Preview.ChangeConversation(tc.ProduceConversation());
            Program.Preview.Resume();
        }
    }
}
